package com.gton.person.service.impl;

import com.gton.person.commons.ResultAdvice;
import com.gton.person.entity.Student;
import com.gton.person.entity.StudentUserInfo;
import com.gton.person.mapper.StudentUserInfoMapper;
import com.gton.person.service.RoleService;
import com.gton.person.service.StudentService;
import com.gton.person.service.StudentUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GuoTong
 * @since 2020-12-18
 */
@Service
@Slf4j
public class StudentUserInfoServiceImpl extends ServiceImpl<StudentUserInfoMapper, StudentUserInfo> implements StudentUserInfoService {

    /**
     * DAO层注入
     */
    @Resource
    private StudentUserInfoMapper studentUserInfoMapper;

    /**
     * 加密依赖
     */
    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    /**
     * 真正的用户类的service
     */
    @Autowired
    private StudentService studentService;

    /**
     * 里面封装了redis的相关操作，和权限相关的业务处理
     */
    @Autowired
    private RoleService roleService;


    /**
     * 注册大逻辑
     * 声明式事物
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, readOnly = false)
    public ResultAdvice userAndRoleRegister(Map<String, Object> map) {
        log.info("注册大逻辑。。。。。");
        //查看传过来没有
        for (Map.Entry<String, Object> s : map.entrySet()) {
            System.out.println(s.getKey() + ":" + s.getValue());
        }
        //注册表字段判断比较
        //获取登录时的用户名
        Object username = map.get("username");
        //空指针处理
        Object userName = Optional.ofNullable(username).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(userName)) {
            return ResultAdvice.error("未携带账号名称");
        }
        //获取登录时的密码
        Object password = map.get("password");
        //空指针处理
        Object passWord = Optional.ofNullable(password).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(passWord)) {
            return ResultAdvice.error("未输入密码");
        }
        Student student = new Student();
        student.setUsername(userName.toString());
        student.setPassword(passWord.toString());

        /*用户详细信息表：
        1.用户头像
        2.*/
        Object headImage = map.get("headImage");
        //空指针处理
        headImage = Optional.ofNullable(headImage).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(headImage)) {
            //前台有默认的，这段可以以舍去
            return ResultAdvice.error("非法操作，采用第三方工具模拟数据：头像未选择");
        }
        /*用户真实姓名*/
        Object useName = map.get("useName");
        //空指针处理
        useName = Optional.ofNullable(useName).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(useName)) {
            return ResultAdvice.error("未填写用户名");
        }
        /*性别*/
        Object sex = map.get("sex");
        //空指针处理
        sex = Optional.ofNullable(sex).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(sex)) {
            return ResultAdvice.error("非法操作，采用第三方工具模拟数据：未填写性别");
        }
        /*用户电话号码*/
        Object telPhone = map.get("telphone");
        //空指针处理
        telPhone = Optional.ofNullable(telPhone).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(telPhone)) {
            return ResultAdvice.error("未填写电话号码");
        }
        /*年龄*/
        Object age = map.get("age");
        //空指针处理
        age = Optional.ofNullable(age).orElse(0);
        //判断是否输入用户名
        if (StringUtils.isEmpty(age)) {
            return ResultAdvice.error("未填写年龄");
        }
        /*家庭住址*/
        Object address = map.get("address");
        //空指针处理
        address = Optional.ofNullable(address).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(address)) {
            return ResultAdvice.error("未填写家庭住址");
        }
        /*邮箱*/
        Object email = map.get("email");
        //空指针处理
        email = Optional.ofNullable(email).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(email)) {
            return ResultAdvice.error("未填写家庭住址");
        }
        /*个人描述*/
        Object descript = map.get("descript");
        //空指针处理
        descript = Optional.ofNullable(descript).orElse("");
        //判断是否输入用户名
        if (StringUtils.isEmpty(descript)) {
            return ResultAdvice.error("未填写家庭住址");
        }
        /*封装数据*/
        StudentUserInfo studentUserInfo = new StudentUserInfo();
        studentUserInfo.setGrade(1);
        /*  studentUserInfo.setSid(student.getId());//必须要自动填充完成之后getId（）才是有值得*/
        studentUserInfo.setSex(sex.toString());
        studentUserInfo.setAddress(address.toString());
        studentUserInfo.setAge(Integer.parseInt(age.toString()));
        studentUserInfo.setDescript(descript.toString());
        studentUserInfo.setEmail(email.toString());
        studentUserInfo.setUseName(useName.toString());
        studentUserInfo.setTelphone(telPhone.toString());
        studentUserInfo.setHeadImage(headImage.toString());
        System.out.println(studentUserInfo);
        //设置级别
        studentUserInfo.setGrade(1);

        /*业务处理*/
        //填充注册表必要字段
        student.setPwdShow(student.getPassword());
        boolean registerIsOk = false;
        int insertStudentUserInfo = 0;
        try {
            //判断传入的参数是否有效
            String errorAdvice = studentService.getResultAdvice(student);
            //如果校验失败就返回错误信息
            if (errorAdvice != null) {
                //如果验证失败，刷新缓存
                /*roleService.updateRedisForDML();*/
                return ResultAdvice.error(errorAdvice);
            }

            //原始密码字段需要加盐加密
            student.setPassword(bCryptPasswordEncoder.encode(student.getPassword()));
            //执行保存操作,用户表保存，然后需要初始化赋予一定的权限
            registerIsOk = studentService.registerUser(student);
            //执行注册后，自动填充ID完成，才能获取
            System.out.println(student.getId());
            //信息用户表外键连接登录用户表
            studentUserInfo.setSid(student.getId());
            insertStudentUserInfo = studentUserInfoMapper.insert(studentUserInfo);
            return registerIsOk && insertStudentUserInfo > 0 ? ResultAdvice.OK() : ResultAdvice.error("注册失败");
        } catch (Exception e) {
            //手动抛异常：手动回滚
            throw e;
        }


    }

    /**
     * 根据登录用户ID查找用户ID
     */
    @Override
    public String getByUserId(int loginId) {
        StudentUserInfo studentUserInfo = studentUserInfoMapper.SelectByLoginId(loginId);
        if(StringUtils.isEmpty(studentUserInfo)){
            return "未找到";
        }
        return studentUserInfo.getId();
    }
}
